/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.wikimark.container;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;

import javax.servlet.ServletOutputStream;

final class ServletBufferedPipe extends ServletOutputStream {
	static final int CHUNK_SIZE = 1 << 15;

	private boolean blocked;

	private boolean closed;

	private int readPos;

	private int writePos;

	private int available;

	private byte[] readBuf;

	private byte[] writeBuf;

	private final byte[] oneBuf = new byte[1];

	private final int chunkSize;

	/**
	 * Default public constructor
	 */
	public ServletBufferedPipe() {
		this(CHUNK_SIZE);
	}

	ServletBufferedPipe(int chunkSize) {
		this.chunkSize = chunkSize;
	}

	LinkedList<byte[]> buffers = new LinkedList<byte[]>();

	final InputStream readStream = new InputStream() {
		@Override
		public int available() throws IOException {
			return getAvailable();
		}

		@Override
		public int read(byte[] arr, int start, int length) throws IOException {
			return ServletBufferedPipe.this.read(arr, start, length, true);
		}

		@Override
		public int read() throws IOException {
			return ServletBufferedPipe.this.read();
		}
	};

	@Override
	public synchronized void write(byte[] arr, int start, int length)
			throws IOException {
		if (closed) {
			throw new IOException("closed");
		}
		if (length == 0) {
			return;
		}
		if (writeBuf == null) {
			writeBuf = new byte[chunkSize];
			buffers.add(writeBuf);
		}
		final int toCurChunk = Math.min(length, chunkSize - writePos);
		System.arraycopy(arr, start, writeBuf, writePos, toCurChunk);
		writePos += toCurChunk;
		if (writePos == chunkSize) {
			writeBuf = null;
			writePos = 0;
		}
		available += toCurChunk;
		if (length > toCurChunk) {
			write(arr, start + toCurChunk, length - toCurChunk);
		}
		if (blocked) {
			blocked = false;
			notifyAll();
		}
	}

	synchronized int getAvailable() {
		return available;
	}

	@Override
	public synchronized void write(int b) throws IOException {
		if (closed) {
			throw new IOException("closed");
		}
		oneBuf[0] = (byte) b;
		write(oneBuf, 0, 1);
	}

	synchronized int read(byte[] arr, int start, int length, boolean block)
			throws IOException {
		
		if (available == 0) {
			if (block) {
				if (closed) {
					return -1;
				}
				blocked = true;
				try {
					wait();
				} catch (InterruptedException e) {
					throw new IOException(e.getMessage());
				}
			} else {
				return 0;
			}
		}
		if (readBuf == null) {
			readBuf = buffers.remove();
		}
		final int fromCurChunk = Math.min(length,
				(readBuf == writeBuf ? writePos : chunkSize) - readPos);
		int read = fromCurChunk;
		System.arraycopy(readBuf, readPos, arr, start, fromCurChunk);
		readPos += fromCurChunk;
		if (readPos == chunkSize) {
			readBuf = null;
			readPos = 0;
		}
		available -= fromCurChunk;
		if (length > fromCurChunk) {
			read += read(arr, start + fromCurChunk, length - fromCurChunk,
					false);
		}
		return read;
	}

	synchronized int read() throws IOException {
		if (closed) {
			return -1;
		}
		read(oneBuf, 0, 1, true);
		return oneBuf[0];
	}

	public synchronized void close() {
		closed = true;
	}
}
